package com.niiwoo.civet.user.service.duboo;

import com.alibaba.dubbo.config.annotation.Service;
import com.niiwoo.civet.account.constant.AccountRegisterErrorCode;
import com.niiwoo.civet.user.dao.entity.OrgUserLogin;
import com.niiwoo.civet.user.dao.entity.OrganizationInfo;
import com.niiwoo.civet.user.dao.mapper.OrgUserLoginMapper;
import com.niiwoo.civet.user.dto.request.OrgUserLoginReqDTO;
import com.niiwoo.civet.user.dto.request.OrganizationInfoReqDTO;
import com.niiwoo.civet.user.dto.request.OrganizationRequestDTO;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.dto.response.OrgInfoRespDTO;
import com.niiwoo.civet.user.dto.response.OrganizationInfoRespDTO;
import com.niiwoo.civet.user.dto.response.organization.OrganizationBaseConfigRespDTO;
import com.niiwoo.civet.user.enums.OrganizationEnum;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.civet.user.service.local.OrganizationService;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Description:
 * @Author:LiJian
 * @Date:2017/12/15
 */
@Service(version = "1.0.0")
public class OrganizationDubboServiceImpl implements OrganizationDubboService {

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private OrgUserLoginMapper orgUserLoginMapper;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Override
    public SimpleOrgInfo getByOrgId(String orgId) {
        OrganizationInfo organizationInfo = organizationService.getByOrgId(orgId);
        if (organizationInfo == null) {
            return null;
        }
        return this.createSimpleOrgInfo(organizationInfo);
    }

    @Override
    public SimpleOrgInfo getByAbbreviation(String abbreviation) {
        OrganizationInfo organizationInfo = organizationService.getByAbbreviation(abbreviation);
        if (organizationInfo == null){
            return null;
        }
        return  this.createSimpleOrgInfo(organizationInfo);
    }

    @Override
	public List<SimpleOrgInfo> queryListByOrgIdSet(Set<String> orgIdSet) {
    	List<SimpleOrgInfo> result = new ArrayList<>();
    	List<OrganizationInfo> organizationInfoList = organizationService.getByOrgIdList(orgIdSet);
        organizationInfoList.forEach(infoList -> result.add(this.createSimpleOrgInfo(infoList)));
        return result;
	}

    @Override
    public SimpleOrgInfo getSimpleOrgInfoByType(OrganizationEnum organizationEnum) {
        if (organizationEnum == null) {
            return null;
        }
        OrganizationInfo organizationInfo = organizationService.getOrganizationInfoByType(organizationEnum.getType());
        if (organizationInfo == null) {
            return null;
        }

        return this.createSimpleOrgInfo(organizationInfo);
    }

    @Override
    public List<SimpleOrgInfo> getGuaranteeAndAntiGuaranteeInfo() {
        List<SimpleOrgInfo> orgInfoList = new ArrayList<>();
        OrganizationInfo guaranteeOrgInfo = organizationService.getOrganizationInfoByType(OrganizationEnum.GUARANTEE_ORG.getType());
        if (guaranteeOrgInfo != null) {
            orgInfoList.add(this.createSimpleOrgInfo(guaranteeOrgInfo));
        }
        OrganizationInfo antiGuaranteeOrgInfo = organizationService.getOrganizationInfoByType(OrganizationEnum.ANTI_GUARANTEE_ORG.getType());
        if (antiGuaranteeOrgInfo != null) {
            orgInfoList.add(this.createSimpleOrgInfo(antiGuaranteeOrgInfo));
        }
        return orgInfoList;
    }

    @Override
    public boolean isCooperate(String orgCode) {
        return organizationService.getEnableOrgInfoByOrgCode(orgCode) != null;
    }

    private SimpleOrgInfo createSimpleOrgInfo(OrganizationInfo organizationInfo) {
        SimpleOrgInfo orgInfo = new SimpleOrgInfo();
        orgInfo.setId(organizationInfo.getId());
        orgInfo.setOrganizationCode(organizationInfo.getOrganizationCode());
        orgInfo.setOrganizationName(organizationInfo.getOrganizationName());
        orgInfo.setType(organizationInfo.getType());
        orgInfo.setAbbreviation(organizationInfo.getAbbreviation());
        orgInfo.setAgentRealName(organizationInfo.getAgentRealName());
        orgInfo.setAgentIdentityCard(organizationInfo.getAgentIdentityCard());
        orgInfo.setAgentPhoneNumber(organizationInfo.getAgentPhoneNumber());
        orgInfo.setRepresentative(organizationInfo.getRepresentative());
        orgInfo.setLegalPersonPhoneNumber(organizationInfo.getLegalPersonPhoneNumber());
        orgInfo.setLegalPersonCertNumber(organizationInfo.getLegalPersonCertNumber());
        orgInfo.setTelephoneNumber(organizationInfo.getTelephoneNumber());
        orgInfo.setEmail(organizationInfo.getEmail());
        orgInfo.setFadadaCacertId(organizationInfo.getFadadaCacertId());
        orgInfo.setInstitutionalReditCode(maskReditCode(organizationInfo.getInstitutionalReditCode()));
        orgInfo.setLogo(organizationInfo.getLogoUrl());
        orgInfo.setPushOrgId(organizationInfo.getPushOrgId());
        orgInfo.setUnifiedSocialCreditCode(organizationInfo.getUnifiedSocialCreditCode());
        orgInfo.setCharterCode(organizationInfo.getCharterCode());
        StringBuilder addSb = new StringBuilder();
        addSb.append(StringUtils.isNotBlank(organizationInfo.getProvince()) ? organizationInfo.getProvince() : "");
        addSb.append(StringUtils.isNotBlank(organizationInfo.getCity()) ? organizationInfo.getCity() : "");
        addSb.append(StringUtils.isNotBlank(organizationInfo.getAddress()) ? organizationInfo.getAddress() : "");
        orgInfo.setAddress(addSb.toString());
        orgInfo.setHeadImg(organizationInfo.getHeadImage());
        orgInfo.setNickName(organizationInfo.getNickName());
        return orgInfo;
    }

    public String maskReditCode(String reditCode) {
        if(StringUtils.isNotEmpty(reditCode) && reditCode.length() > 4) {
            return reditCode.substring(0, 4) + "**********" + reditCode.substring(reditCode.length() - 4, reditCode.length());
        } else {
            return reditCode;
        }
    }

    @Override
    public boolean updateUserOrgInfo(OrganizationRequestDTO orgInfoReqDto) {
        return organizationService.updateUserOrgInfo(orgInfoReqDto);
    }

    @Override
    public String getOrgId(String orgCode) {
        OrganizationInfo orgInfo = organizationService.getOrgInfoByOrgCode(orgCode);
        return orgInfo == null ? null : orgInfo.getId();
    }
    
    @Override
    public OrganizationBaseConfigRespDTO selectOrganizationBaseConfigByOrgId(String orgId) {
        return organizationService.selectOrganizationBaseConfigByOrgId(orgId);
    }

    @Override
    public boolean isFullFreezePerformance(String orgId) {
        return organizationService.isFullFreezePerformance(orgId);
    }

    @Override
    public Integer checkAgentUserRealName(String realName, String identityCard) {
        return organizationService.checkAgentUserRealName(realName, identityCard);
    }

    /**
     * 获取机构信息
     * @param orgId
     * @return
     */
    @Override
    public OrgInfoRespDTO queryOrgInfoById(String orgId) {
        OrganizationInfo organizationInfo = organizationService.getByOrgId(orgId);
        if (organizationInfo == null) {
            return null;
        }
        OrgInfoRespDTO orgInfo = new OrgInfoRespDTO();
        BeanUtils.copyProperties(organizationInfo,orgInfo);
        orgInfo.setOrgShortName(organizationInfo.getAbbreviation()); //机构简称
        orgInfo.setOrgName(organizationInfo.getOrganizationName());
        return orgInfo;
    }

    public String loadValidOrgId(String orgCode){
        String orgId = getOrgId(orgCode);
        if(StringUtils.isBlank(orgId)){
            throw new BizException(AccountRegisterErrorCode.ORG_NOT_EXIST);
        }
        return orgId;
    }

    public BigDecimal getMaxOrgRate(){
        return organizationService.getMaxOrgRate();
    }


    @Override
    public OrganizationInfoRespDTO selectOrganizationInfoByAgentUserName(String agentUserName) {
        return organizationService.selectOrganizationInfoByAgentUserName(agentUserName);
    }

    @Override
    public boolean sendSmsByLogin(String mobliePhone) {
        Assert.notNull(mobliePhone, "USR19006");
        return organizationService.sendSmsByLogin(mobliePhone);

    }

    @Override
    public int updatePassword(OrganizationInfoReqDTO organizationInfoReqDTO) {
        return organizationService.updatePassword(organizationInfoReqDTO);
    }

    @Override
    public int insertLoginRecord(OrgUserLoginReqDTO orgUserLoginReqDTO) {
        OrgUserLogin orgUserLogin = new OrgUserLogin();
        BeanUtils.copyProperties(orgUserLoginReqDTO, orgUserLogin);
        orgUserLogin.setId(snowflakeIdWorker.nextId() + "");
        return orgUserLoginMapper.insert(orgUserLogin);
    }

    @Override
    public SimpleOrgInfo queryOrgBySocialCreditCode(String unifiedSocialCreditCode) {
        OrganizationInfo organizationInfo = organizationService.getOrgInfoBySocialCreditCode(unifiedSocialCreditCode);
        if (organizationInfo == null) {
            return null;
        }
        return this.createSimpleOrgInfo(organizationInfo);
    }
}
